<template>
  <div class="page-container">
    <el-form label-position="top" class="custom-form">
      <el-form-item label="PDF文件" class="form-item-group">
        <el-input
          v-model="pdfPathsText"
          placeholder="选择PDF文件（支持单个或多个）"
          readonly
          class="form-input"
        >
          <template #append>
            <el-button
              type="primary"
              class="browse-btn"
              @click="selectPdfFilesFn"
              >浏览</el-button
            >
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="输出目录" class="form-item-group">
        <el-input
          v-model="outputDir"
          placeholder="选择图片输出目录"
          readonly
          class="form-input"
        >
          <template #append>
            <el-button
              type="primary"
              class="browse-btn"
              @click="selectOutputDirFn"
              >浏览</el-button
            >
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="输出格式" class="form-item-group">
        <el-select
          v-model="outputFormat"
          style="width: 100%"
          class="form-select"
          :disabled="isMultipleFiles"
        >
          <el-option
            v-for="option in outputFormatAry"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
        <div v-if="isMultipleFiles" class="form-help">
          多个PDF文件时，保持原始图片格式
        </div>
      </el-form-item>

      <el-form-item label="输出名称前缀" class="form-item-group">
        <el-input
          v-model="filePrefix"
          placeholder="输出图片的名称前缀"
          class="form-input"
          :disabled="isMultipleFiles"
        />
        <div v-if="isMultipleFiles" class="form-help">
          多个PDF文件时，自动使用PDF名称作为前缀
        </div>
        <div v-else class="form-help">留空则使用PDF文件名作为前缀</div>
      </el-form-item>

      <el-form-item label="转换类型" class="form-item-group">
        <el-select
          v-model="convertType"
          placeholder="请选择转换类型"
          class="form-select"
        >
          <el-option
            v-for="item in convertTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="图片尺寸" class="form-item-group">
        <el-input
          v-model="imageWidth"
          placeholder="宽度（像素，留空则保持原图）"
          class="form-input"
          type="number"
          min="0"
        />
        <div class="form-help">
          仅填写宽度将保持原始比例，留空则使用原图大小
        </div>
        <el-input
          v-model="imageHeight"
          placeholder="高度（像素，留空则保持原图）"
          class="form-input"
          type="number"
          min="0"
          style="margin-top: 10px"
        />
        <div class="form-help">
          仅填写高度将保持原始比例，均不填写则使用原图大小
        </div>
      </el-form-item>

      <el-form-item class="progress-section">
        <div class="progress-label">处理进度</div>
        <el-progress
          :percentage="progress"
          :status="progressStatus"
          :text-inside="true"
          :stroke-width="18"
          class="custom-progress"
        />
      </el-form-item>

      <el-form-item v-if="statusVisible" class="status-section">
        <el-alert
          :title="statusMessage"
          :type="statusType"
          show-icon
          class="status-alert"
        />
      </el-form-item>

      <el-form-item class="button-section">
        <el-button
          type="success"
          @click="extractImagesFn"
          :disabled="isProcessing"
          class="primary-btn"
          >开始提取</el-button
        >
        <el-button type="default" @click="clearFormFn" class="secondary-btn"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';

// 响应式数据
const pdfPaths = ref([]);
const pdfPathsText = ref('');
const outputDir = ref('');
const outputFormat = ref('png');
const filePrefix = ref('');
const imageWidth = ref('');
const imageHeight = ref('');
const progress = ref(0);
const progressStatus = ref('');
const statusMessage = ref('');
const statusType = ref('info');
const statusVisible = ref(false);
const isProcessing = ref(false);
const convertType = ref('extractRawImages'); // 默认提取原始图片

// 输出格式选项
const outputFormatAry = reactive([
  { label: 'PNG', value: 'png' },
  { label: 'JPEG', value: 'jpeg' },
  { label: 'WEBP', value: 'webp' },
  { label: 'BMP', value: 'bmp' }
]);

// 转换类型选项
const convertTypeOptions = reactive([
  { label: '将PDF每页转成图片', value: 'convertPages' },
  { label: '提取原始图片', value: 'extractRawImages' }
]);

// 计算属性
const isMultipleFiles = computed(() => pdfPaths.value.length > 1);
const canStartProcessing = computed(() => pdfPaths.value.length > 0 && outputDir.value !== '');

// 选择PDF文件
const selectPdfFilesFn = async () => {
  try {
    const paths = await window.electronAPI.openFileDialog({
      title: '选择PDF文件',
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: 'PDF文件', extensions: ['pdf'] }]
    });

    if (paths && paths.length > 0) {
      // 确保pdfPaths.value是只包含字符串的数组
      pdfPaths.value = Array.isArray(paths)
        ? paths.map(String)
        : [String(paths)];
      pdfPathsText.value = pdfPaths.value.length === 1 ?
        pdfPaths.value[0] :
        `${pdfPaths.value.length} 个PDF文件`;
    }
  } catch (error) {
    showStatusFn('选择PDF文件失败', 'error');
  }
};

// 选择输出目录
const selectOutputDirFn = async () => {
  try {
    const paths = await window.electronAPI.openDirectoryDialog({
      title: '选择输出目录'
    });

    if (paths.length > 0) {
      outputDir.value = paths[0];
    }
  } catch (error) {
    showStatusFn('选择输出目录失败', 'error');
  }
};

// 显示状态信息
const showStatusFn = (message, type) => {
  statusMessage.value = message;
  statusType.value = type;
  statusVisible.value = true;
};

// 更新进度值
const progressValueUpdateFn = (value) => {
  // 修复：进度值保留两位小数
  progress.value = parseFloat(value.toFixed(2));
  if (progress.value >= 100) {
    progress.value = 100;
    progressStatus.value = 'success';
  } else {
    progressStatus.value = '';
  }
};

// 开始提取图片
const extractImagesFn = async () => {
  // 确保pdfPaths.value是数组
  const safePdfPaths = Array.isArray(pdfPaths.value) ? pdfPaths.value : [];
  if (safePdfPaths.length === 0) {
    showStatusFn('请选择PDF文件', 'error');
    return;
  }

  if (!outputDir.value) {
    showStatusFn('请选择输出目录', 'error');
    return;
  }

  // 重置进度状态
  isProcessing.value = true;
  progress.value = 0;
  progressStatus.value = '';
  statusVisible.value = false;
  showStatusFn('开始提取图片...', 'info');

  try {
    // 准备配置，确保所有值都是可序列化的
    const config = {
      pdfPaths: safePdfPaths.map(String),
      outputDir: String(outputDir.value),
      outputFormat: String(outputFormat.value),
      outputQuality: 90, // 默认质量
      width: imageWidth.value ? parseInt(imageWidth.value) : 0,
      height: imageHeight.value ? parseInt(imageHeight.value) : 0,
      filePrefix: String(filePrefix.value),
      isMultipleFiles: Boolean(isMultipleFiles.value),
      convertType: convertType.value,
    };

    // 调用IPC处理函数
    const result = await window.electronAPI.pdfToImages(config);

    if (result.success) {
      showStatusFn(result.message, 'success');
      progressValueUpdateFn(100);
    } else {
      showStatusFn(result.message, 'error');
    }
  } catch (error) {
    showStatusFn('提取失败: ' + error.message, 'error');
  } finally {
    isProcessing.value = false;
  }
};

// 清空表单
const clearFormFn = () => {
  pdfPaths.value = [];
  pdfPathsText.value = '';
  outputDir.value = '';
  outputFormat.value = 'png';
  filePrefix.value = '';
  imageWidth.value = '';
  imageHeight.value = '';
  progress.value = 0;
  progressStatus.value = '';
  statusVisible.value = false;
};

// 监听进度更新
const progressUpdateFn = (progressData) => {
  if (progressData.type === 'pdf-to-images') {
    if (progressData.error) {
      showStatusFn('提取失败: ' + progressData.error, 'error');
      isProcessing.value = false;
      return;
    }
    progressValueUpdateFn(progressData.progress);
  }
};

// 生命周期钩子
onMounted(() => {
  window.electronAPI.onProgressUpdate(progressUpdateFn);
});

onUnmounted(() => {
  window.electronAPI.removeProgressListener();
});
</script>

<style scoped>
</style>
